/*var showFees = function(outData) {
	if (!outData) {
		alert("费率数据为空！");
		return;
	}

	if (outData.VFEE_INFO == null) {
		alert("费率数据为空！");
		return;
	}

	console.info(outData);

	var vw = outData.VFEE_INFO; //outData.VFEE_INFO instanceof Object?[{}]:outData.VFEE_INFO;
	console.info(vw);
	if (vw.length == 0) { //查询成功但是返回资费列表info为空
		var str1 = "<option value='-1'>查无资费</option>";
		$("#fee").empty().append(str1);
		return;
	}
	var str = "<option value='-1'>请选择V网资费</option>";
	for (var i = 0; i < vw.length; i++) {
		var feeName = vw[i].FEE_NAME.substring(vw[i].FEE_NAME.indexOf('>') + 1, vw[i].FEE_NAME.length);
		str += "<option value=\"" + vw[i].FEE_NUM + "\">" + feeName + "</option>";
	}
	$("#fee").children().remove();
	$("#fee").append(str);

};

var loadFees = function() {
	//TODO: 去掉PHONE_NO
	var params = {
		"BODY": {
			"PHONE_NO": getMobile(),
			"WORN_SERV_CODE": "sVpmnFCodeCfm",
			"LOGIN_NO": getEmpCode(),
			"COMMON_INFO": {
				"PROVINCE_GROUP": "10008"
			}
		}
	};
	sendRestPostAjax(params, Constants.rpcCrmHost + "sUserOrdQry?token=" + getToken(), showFees);
};
*/
var checkPhone = function(phone) {
	var reg = Constants.cmccMobileReg; // /^1[3|4|5|7|8]\\d{9}$/;
	if (reg.test(phone)) {
		return true;
	}
	return false;
};

var checkShortNum = function(shortNum) {
	if ((shortNum) && (shortNum.length > 2) && (shortNum.length < 7) && (shortNum.substring(0, 1) == 6)) {
		return true;
	}
	return false;
};

var checkFee = function(fee) {
	if ((fee) && (fee != "-1")) {
		return true;
	}
	return false;
};

var addVnetRecord = function(){
	var params= {"userid": parseInt(getParamValue("userId"), 10),"opType":0,"vType":0,"vCode":$("#grpId").html(),"vName":$("#grpName").html(),"vMember":$("#phone").val(),"vShort":$("#shortNum").val(),"vPkgRate":$("#fee").val(),"vPkgName":$("#fee").find("option:selected").html()};

	 $.ajax({
		    type: "post",
		    data: JSON.stringify(params),
		    url: Constants.apiV2Host + "h5/vnetH5/operate",
		    dataType: "json",
		    async: true,
	    contentType: "application/json",
      headers: {
      	'Content-Type': 'application/json',
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(data) {
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }
		        console.log(data);
		        // var returnData = data.data;
		        if(data.ResultCode!=1000){
		          console.log("接口返回失败！code:"+data.ResultCode);
		          return;
		        }
		    },
		    error : function(textStatus) {
		      console.log("network error.");
		    }
		  });
}

var addCallback = function() {
	//添加成功后，需要向数据库写入记录。
	addVnetRecord();

	alert("添加V网成员" + $("#phone").val() + "成功！");

};

var add = function() {
	var params = {
		"BODY": {
			"WORN_SERV_CODE": "sEsopVMbrAdd",
			"COMMON_INFO": {
				"PROVINCE_GROUP": "10008"
			},
			"UNIT_ID": $("#grpId").html(),
			"PHONE_NO": $("#phone").val(),
			"PKG_TYPE": $("#fee").val(),
			"SHORT_NO": $("#shortNum").val(),
			"LOGIN_NO": getEmpCode(),
			"IMEI_NO": ""
		}
	};
	
	sendRestPostAjaxWithModal(params, Constants.rpcCrmHost + "s4000Cfm?token=" + getToken(), addCallback,$('#modal'));
	
};


var getCampusVcodeCallBack = function(outData,grpId) {
	if (!outData) {
	  alert("查询结果为空，请确认集团编码");
	  return;
	}
	console.info(outData);
	if (!outData.VGRP_INFO) {
	  alert("查不到V网，请确认集团编码或者权限");
	  return;
	 }
	
	 show($("#banli"));
	 $("#grpId").html(grpId);
	 $("#grpName").html(outData.VGRP_INFO.VGRP_NAME);
	
	 setCookie("last_grpId",grpId);
};

var getCampusVcode = function(groupId) {
	curGroupId = groupId;
	//TODO: 去掉PHONE_NO
	var params = {
	  "BODY": {
	    "PHONE_NO": getMobile(),
	    "WORN_SERV_CODE": "sEsopVGroupNo",
	    "LOGIN_NO": getEmpCode(),
	    "UNIT_ID": groupId,
	    "COMMON_INFO": {
	      "PROVINCE_GROUP": "10008"
	    }
	  }
	};
	//$('#modal').modal('open');
	  
	  $.ajax({
	    type: "post",
	    contentType: "application/json",
	    data: JSON.stringify(params),
	    url:  Constants.rpcCrmHost +"sUserOrdQry?token=" + getToken(),
	    dataType: "json",
	    async: true,
      headers: {
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(data) {
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }
	    	//$('#modal').modal('close');
	      console.log("data = "+JSON.stringify(data));
	      var returnData = data.ROOT;
	      console.info(returnData);
	      
	      if(returnData.RETURN_CODE!=0){
	    	var msg = returnData.DETAIL_MSG?returnData.DETAIL_MSG:returnData.RETURN_MSG;
	        alert(msg);
	        console.log("获取RPC接口返回失败！code:"+returnData.RETURN_CODE);
	        return;
	      }
	      
	      getCampusVcodeCallBack(returnData.OUT_DATA,groupId);
	    },
	    error : function(textStatus) {
	    	//$('#modal').modal('close');
	        alert("网络或服务器异常，请稍后再试！");
	        console.info("request error:");
	    }
	  });
};

var resetData=function(){
	 hide($("#banli"));
	 
	 $("#grpId").html("");
	 $("#grpName").html("");
	 $("#phone").val("");
	 $("#shortNum").val("");
};

$(function() {
	console.log("grpId:" + getParamValue("group_no"));

	resetData();
	$("#keyword").val(getCookie("last_grpId"))

	$("#submit").on("click", function() {
		 var groupId=$("#grpId").html();
		 var groupName=$("#grpName").html();
		 if((!groupId)||(!groupName)){
			 alert("查询到集团后方可进行业务办理！");
			 return;
		 }
		 
		var phone = $("#phone").val();
		var shortNum = $("#shortNum").val();
		
		if (!checkPhone(phone)) {
			if(phone.length==11){
				alert("仅支持移动手机号码！");
			}else{
				alert("请输入11位移动手机号码！");
			}

			return;
		}
		
		var smscode= $("#smscode").val();
		if(!smscode){
			alert("请输入短信校验码！");
			return;
		}
		if(!checkNumber(smscode)){
			alert("仅支持纯数字短信校验码！");
			return;
		}
		
		if (!checkShortNum(shortNum)) {
			alert("请输入以6开头且6位数以内的短号，如654321");
			return;
		}

		if (!checkFee($("#fee").val())) {
			alert("请选择V网资费");
			return;
		}

		verifySms(phone,smscode,add);

	});
	
	$("#cancel").on("click", function() {
		window.history.go(-1);

	});

	$("#search_button").on("click", function() {
		resetData();
		var key = $("#keyword").val();
		if((!key)||(!checkNumber(key))) {
			alert("请输入纯数字的集团编码！");
			return;
		}
		getCampusVcode(key);

	});

	$("#getSMS").on("click", function() {
		sendSms($("#phone").val());
	});
});